import base64
import json
import locale
import os
import random
import re
import threading
import time
import uuid
from datetime import datetime, timezone
from urllib.parse import urlencode, urlparse, parse_qs, quote

import msgpack
from google.protobuf import json_format

import Global
from Comm.ProxyUtil import ProxyUtil
from HTTP.HttpUtil import HttpUtil
from Res.Resources import Resources
from Script.protobuf import protocol_pb2
from 加密.AESHelper import AESHelper
from 加密.Crpty import Crpty


class GameFun:
    appVersion = "1.06.08"
    DLCVersion = '340'
    GateWay_Key =bytes.fromhex("9ac488d72c2613e55c2e4d12125f5376555c159b78d2675b378259577f331c4e")
    Game_Key = bytes.fromhex("402e9fd6462897e67150370a5036f192d9f7d694aba1f02d72e32d9e5332596c")
    Nonce = bytes.fromhex("e190f6998fcfebd5")
    def __init__(self,player_id,device_id ="",android_id="",token=None,index=-1,proxy_info=None,country_code="global",isBind=False,gamedata=None):
        self.game_index = index

        self.game = gamedata
        self.country = country_code
        self.host = "https://apis.netmarble.com"  # 台服
        self.device_id = device_id or uuid.uuid4().hex
        self.android_id = android_id or uuid.uuid4().hex[:16]
        self.authToken = token
        self.player_id = player_id
        r = random.Random()
        randIndex = r.randint(0, len(Global.G_Dbc['phone']) - 1)
        self.brand = Global.G_Dbc['phone'][randIndex]["brand"]
        self.model = Global.G_Dbc['phone'][randIndex]["model"]
        self.androidver = r.randint(10, 14)
        self.device = {
            "osVersion": f"Android OS {self.androidver}",
            "deviceName": f"{self.model}"
        }


        self.advertisingId=str(uuid.uuid1())
        self.adjustDeviceId=uuid.uuid4().hex
        if proxy_info is None:
            self.proxy={}
            self.proxy["type"]=self.game.data["proxyType"]
            self.proxy["ip"] = self.game.data["proxyIP"]
            self.proxy["port"] = self.game.data["proxyPort"]
            self.proxy["user"] = self.game.data["proxyUser"]
            self.proxy["pass"] = self.game.data["proxyPass"]
        else:
            self.proxy = proxy_info
        self.http_util =HttpUtil()

    def __del__(self):
        if hasattr(self, 'http_util'):
            del self.http_util

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if hasattr(self, 'http_util'):
            del self.http_util
        return False  # 不处理异常，继续抛出

    # def Post(self, url, data):
    #     status_code = 0
    #     repons = None
    #     erro = {
    #         "code": 0,
    #         "msg": ''
    #     }
    #
    #     grpc_status = 0
    #     data = msgpack.packb(data | self.get_common())
    #     common_header = bytes.fromhex(self.CommonHeader)
    #     if not self.uuid:
    #         self.uuid = str(uuid.uuid4())
    #         #self.game.data['userId'] = self.uuid
    #     if not self.sid:
    #         sid = Crpty.md5(str(self.ViewerID) + str(self.uuid) + self.md5_key)
    #     else:
    #         sid = Crpty.md5(str(self.sid) + self.md5_key)
    #     uuid_bytes=bytes.fromhex(self.uuid.replace("-",""))
    #     sid_bytes = bytes.fromhex(sid)
    #     random_bytes =  uuid.uuid4().bytes + uuid.uuid4().bytes
    #     token_bytes = base64.b64decode(self.authToken)
    #     len_header = len(common_header) + len(sid_bytes) + len(uuid_bytes) + len(random_bytes) + len(token_bytes)
    #     post_data = len_header.to_bytes(length=4,byteorder='little') + common_header + sid_bytes + uuid_bytes + random_bytes +token_bytes
    #
    #     aes_key = base64.b64encode(uuid.uuid4().bytes[:12].hex().encode())
    #     aes_iv =uuid_bytes[:8].hex().encode()
    #     with AESHelper(key=aes_key, iv=aes_iv) as aes:
    #         #aes = AESHelper(key=aes_key, iv=aes_iv)
    #         encry_data = aes.encrypt(int.to_bytes(len(data),4,'little') + data)
    #     post_data = post_data + encry_data + aes_key
    #     b64_data = base64.b64encode(post_data).decode("utf-8")
    #
    #     r = random.Random()
    #     for _ in range(3):
    #         try:
    #             headers = {
    #                 "APP-VER": self.appVersion,
    #                 "Content-Type": "application/x-msgpack",
    #                 "Device": '2',#安卓是2  PC是4
    #                 "RES-VER": self.RES_VER,
    #                 "SID": sid,
    #                 "User-Agent": "UnityPlayer/2019.4.21f1 (UnityWebRequest/1.0, libcurl/7.52.0-DEV)",
    #                 "ViewerID": str(self.ViewerID),
    #                 "X-Unity-Version": '2019.4.21f1',
    #             }
    #             response_headers = {}
    #             repons, status_code, erro = self.http_util.post(url=url, data=b64_data.encode(), headers=headers,response_headers=response_headers, proxy=self.proxy,timeout=30,enable_Http2=False)  # ,
    #             if status_code != 200 and (erro['code'] < 0 or erro['code'] == 0 or erro['code'] == 28 or erro['code'] == 7 or erro[ 'code'] == 56 or erro['code'] == 483 or erro['code'] == 35 or erro['code'] == 92):
    #                 # Global.LOGD(self.game_index,'更换IP中')
    #                 self.proxy = ProxyUtil.get_ip()
    #                 if self.game:
    #                     self.game.proxy = self.proxy
    #                 else:
    #                     self.game.proxy = self.proxy
    #                 if self.game.proxy:
    #                     self.game.data["proxyIP"] = self.game.proxy.get("ip", "") + ":" + str(
    #                         self.game.proxy.get("port", 0))
    #                 continue
    #             if 'grpc-status' in response_headers:
    #                 grpc_status = int(response_headers['grpc-status'])
    #                 erro['code'] = grpc_status
    #                 erro['msg'] = response_headers.get('grpc-message', '')
    #             if repons is not None and len(repons) > 0:
    #                 repons_encry_data = base64.b64decode(repons)
    #                 response_data =repons_encry_data[:len(repons_encry_data)-32]
    #                 aes_key =repons_encry_data[len(repons_encry_data)-32:]
    #                 with AESHelper(key=aes_key, iv=aes_iv) as aes:
    #                     #aes = AESHelper(key=aes_key, iv=aes_iv)
    #                     decry_data = aes.decrypt(response_data)
    #                 if decry_data:
    #                     repons = msgpack.unpackb(decry_data[4:], raw=False, strict_map_key=False)
    #                     self.sid = repons['data_headers']['sid']
    #                     if repons.get('data',None):
    #                         resource_version =repons['data'].get('resource_version',None)
    #                         if resource_version:
    #                             self.RES_VER = resource_version
    #                 else:
    #                     erro['code'] = -1
    #                     erro['msg'] = "解密数据错误"
    #                 break
    #             if grpc_status != 0:
    #                 break
    #             if self.proxy == None or not self.proxy.get('ip'):  # 没有设置代理或者取不到ip字段直接返回
    #                 break
    #         except Exception as e:
    #             Global.LOGE(self.game_index, F"Post异常:status_code:{status_code},erro:{e},repons:{repons}")
    #     return repons, status_code, erro

    def sign_up(self):
        status_code = None
        erro = None
        try:
            url = f"{self.host}/cpp-auth/v1/sign-up"

            data = {"nmDeviceKey":self.android_id.upper(),"deviceKey":self.device_id.upper(),"countryCode":self.country,"os":"ANDROID"}
            headers={
                "User-Agent": f"ProjectRE/UE5-CL-0 (http-legacy) Android/{self.androidver}",
                "buildCode":"A",
                "gameCode": "tskgb",
                "Content-Type": "application/json"
            }
            response_headers={}
            repons, status_code, erro = self.http_util.post(url=url, data=json.dumps(data).encode(), headers=headers,response_headers=response_headers, proxy=self.proxy,timeout=30)
            if status_code!=200:
                Global.LOGE(self.game_index, f"sign_up失败:{status_code}")
                return False,status_code,erro
            if repons:
                repons =json.loads(repons)
                result_code =repons['errorCode']
                errorMessage = repons['errorMessage']
                if result_code == 0:
                    self.player_id = repons['resultData']['playerInfo']['player']['playerId']
                    return True, status_code, repons.get("resultData", None)
                else:
                    Global.LOGE(self.game_index, f"sign_up出错:{result_code}")
                return False,result_code,errorMessage
        except Exception as e:
            Global.LOGE(self.game_index, f"sign_up异常:{e}")
        return False,status_code,erro

    def sign_in(self):
        status_code = None
        erro = None
        try:
            url = f"{self.host}/cpp-auth/v1/sign-in"

            data = {"nmDeviceKey":self.android_id.upper(),"deviceKey":self.device_id.upper(),"countryCode":self.country,"os":"ANDROID","playerId": self.player_id}
            headers={
                "User-Agent": f"ProjectRE/UE5-CL-0 (http-legacy) Android/{self.androidver}",
                "buildCode":"A",
                "gameCode": "tskgb",
                "Content-Type": "application/json"
            }
            response_headers={}
            repons, status_code, erro = self.http_util.post(url=url, data=json.dumps(data), headers=headers,response_headers=response_headers, proxy=self.proxy,timeout=30)
            if status_code!=200:
                Global.LOGE(self.game_index, f"sign_in失败:{status_code}")
                return False,status_code,erro
            if repons:
                repons =json.loads(repons)
                result_code =repons['errorCode']
                errorMessage = repons['errorMessage']
                if result_code == 0:
                    self.authToken = repons['resultData']['accessToken']
                    return True, status_code, repons
                else:
                    Global.LOGE(self.game_index, f"sign_in出错:{result_code}")
                return False,result_code,errorMessage
        except Exception as e:
            Global.LOGE(self.game_index, f"sign_in异常:{e}")
        return False,status_code,erro
    def ResetResult(self):
        self.game.Result ={}
    def WaitResult(self):
        try:
            self.ResetResult()
            start_times = time.time()
            tx = None
            if self.game.GateWay:
                tx = self.game.GateWay
            elif self.game.Game:
                tx = self.game.Game
            while tx.connected:
                if self.game.Result:
                    break
                else:
                    time.sleep(0.5)
                lost_times = time.time()
                if (lost_times - start_times) >= 60:  # 设置超时
                    break
        except Exception as e:
            Global.LOGE(self.game_index,f"[异常]->WaitResult：{e}")
    def Req_CALoginReq(self):
        CALoginReq = protocol_pb2.CALoginReq()
        CALoginReq.CurrentVersion =5
        CALoginReq.Pid = self.player_id
        if self.country=="KR":
            CALoginReq.LanguageID =1
        elif self.country=="JP":
            CALoginReq.LanguageID = 2
        else:
            CALoginReq.LanguageID = 4
        CALoginReq.IsReconnect =False
        CALoginReq.AuthToken =self.authToken
        CALoginReq.NetmarbleSDKAuth =True
        CALoginReq.PlatformType =protocol_pb2.EPlatformType.AOS
        CALoginReq.AppVersion = GameFun.appVersion
        CALoginReq.IP = ""
        CALoginReq.SequenceMaintenanceLogin =True
        CALoginReq.JoinedCountry =self.country
        isSend =self.game.Game.SendPacket(CALoginReq)
        self.WaitResult()
        return isSend
    def Req_CAChangePlayerNickNameReq(self,name):
        CAChangePlayerNickNameReq = protocol_pb2.CAChangePlayerNickNameReq()
        CAChangePlayerNickNameReq.NickName = name
        CAChangePlayerNickNameReq.IsTutorial =True
        isSend =self.game.Game.SendPacket(CAChangePlayerNickNameReq)
        self.WaitResult()
        return isSend

    def Req_CAGetPlayerReq(self):
        CAGetPlayerReq = protocol_pb2.CAGetPlayerReq()
        isSend = self.game.Game.SendPacket(CAGetPlayerReq)
        #self.WaitResult()
        return isSend
    def Req_CAPurchaseDeliveryReq(self):
        CAPurchaseDeliveryReq = protocol_pb2.CAPurchaseDeliveryReq()
        isSend = self.game.Game.SendPacket(CAPurchaseDeliveryReq)
        #self.WaitResult()
        return isSend
    def Req_CATutorialStartReq(self,id):
        CATutorialStartReq = protocol_pb2.CATutorialStartReq()
        CATutorialStartReq.TutorialID = id
        isSend = self.game.Game.SendPacket(CATutorialStartReq)
        self.WaitResult()
        return isSend
    def Req_CATutorialEndReq(self,id):
        CATutorialEndReq = protocol_pb2.CATutorialEndReq()
        CATutorialEndReq.TutorialIDs.append(id)
        CATutorialEndReq.IsForcedEnd = True
        isSend = self.game.Game.SendPacket(CATutorialEndReq)
        self.WaitResult()
        return isSend
    def Req_CAGetMailListReq(self,PageNum=1):
        CAGetMailListReq = protocol_pb2.CAGetMailListReq()
        CAGetMailListReq.PageNum = PageNum
        isSend = self.game.Game.SendPacket(CAGetMailListReq)
        self.WaitResult()
        return isSend
    def Req_CAMailReadAllReq(self):
        CAMailReadAllReq = protocol_pb2.CAMailReadAllReq()
        isSend = self.game.Game.SendPacket(CAMailReadAllReq)
        self.WaitResult()
        return isSend
    def Req_CAMailDeleteAllReq(self):
        CAMailDeleteAllReq = protocol_pb2.CAMailDeleteAllReq()
        isSend = self.game.Game.SendPacket(CAMailDeleteAllReq)
        self.WaitResult()
        return isSend
    def Req_NetAliveReq(self):
        NetAliveReq = protocol_pb2.NetAliveReq()
        NetAliveReq.RequestMS = int(time.time())*1000
        isSend = self.game.Game.SendPacket(NetAliveReq)
        return isSend
    def Req_CAEnterStageReq(self,StageId,EnterType = 0,IsRepetitionDeck = False):
        CAEnterStageReq = protocol_pb2.CAEnterStageReq()
        CAEnterStageReq.StageId = StageId
        CAEnterStageReq.EnterType = EnterType
        CAEnterStageReq.IsRepetitionDeck = IsRepetitionDeck
        isSend = self.game.Game.SendPacket(CAEnterStageReq)
        self.WaitResult()
        return isSend
    def Req_CAReadyStageReq(self):
        CAReadyStageReq = protocol_pb2.CAReadyStageReq()
        isSend = self.game.Game.SendPacket(CAReadyStageReq)
        return isSend
    def Req_CAQuickAnimationReq(self,Flag = False):
        CAQuickAnimationReq = protocol_pb2.CAQuickAnimationReq()
        CAQuickAnimationReq.Flag = Flag
        isSend = self.game.Game.SendPacket(CAQuickAnimationReq)
        return isSend
    def Req_CAAutoSkillReq(self,IsAutoSkill = False):
        CAAutoSkillReq = protocol_pb2.CAAutoSkillReq()
        CAAutoSkillReq.IsAutoSkill = IsAutoSkill
        isSend = self.game.Game.SendPacket(CAAutoSkillReq)
        return isSend
    def Req_CAAutoSkillReq(self,IsAutoSkill = False):
        CAAutoSkillReq = protocol_pb2.CAAutoSkillReq()
        CAAutoSkillReq.IsAutoSkill = IsAutoSkill
        isSend = self.game.Game.SendPacket(CAAutoSkillReq)
        return isSend
    def Req_CAStartStageReq(self):
        CAStartStageReq = protocol_pb2.CAStartStageReq()
        isSend = self.game.Game.SendPacket(CAStartStageReq)
        return isSend
    def Req_CAStartRoundReq(self):
        CAStartRoundReq = protocol_pb2.CAStartRoundReq()
        isSend = self.game.Game.SendPacket(CAStartRoundReq)
        return isSend
    def Req_CASavePlayerDeckReq(self,deck_list,FormationGroup,deck_type=1):
        CASavePlayerDeckReq = protocol_pb2.CASavePlayerDeckReq()
        CASavePlayerDeckReq.Deck.DeckType = deck_type
        CASavePlayerDeckReq.Deck.DeckPositionUID1 = 0  # int64
        CASavePlayerDeckReq.Deck.DeckPositionUID2 = 0
        CASavePlayerDeckReq.Deck.DeckPositionUID3 = 0
        CASavePlayerDeckReq.Deck.DeckPositionUID4 = 0
        CASavePlayerDeckReq.Deck.DeckPositionUID5 = 0
        CASavePlayerDeckReq.Deck.PetPositionUID = 0
        for index, value in enumerate(deck_list, start=0):
            if index ==0:
                CASavePlayerDeckReq.Deck.DeckPositionUID1 = int(value)
            elif index ==1:
                CASavePlayerDeckReq.Deck.DeckPositionUID2 = int(value)
            elif index ==2:
                CASavePlayerDeckReq.Deck.DeckPositionUID3 = int(value)
            elif index ==3:
                CASavePlayerDeckReq.Deck.DeckPositionUID4 = int(value)
            elif index ==4:
                CASavePlayerDeckReq.Deck.DeckPositionUID5 = int(value)
        CASavePlayerDeckReq.Deck.FormationGroup=FormationGroup
        CASavePlayerDeckReq.UsePreset=False
        isSend = self.game.Game.SendPacket(CASavePlayerDeckReq)
        self.WaitResult()
        return isSend
    def Req_CAGetGachaReq(self):
        CAGetGachaReq = protocol_pb2.CAGetGachaReq()
        isSend = self.game.Game.SendPacket(CAGetGachaReq)
        self.WaitResult()
        return isSend
    def Req_CADrawGachaReq(self,GachaTID,MultipleDraw=False,UseTicket=True):
        CADrawGachaReq = protocol_pb2.CADrawGachaReq()
        CADrawGachaReq.GachaTID = GachaTID
        CADrawGachaReq.MultipleDraw = MultipleDraw
        CADrawGachaReq.UseTicket = UseTicket
        isSend = self.game.Game.SendPacket(CADrawGachaReq)
        self.WaitResult()
        return isSend
    def Req_CASetPreOrderSkillReq(self,DeckType,hero_list):
        CASetPreOrderSkillReq = protocol_pb2.CASetPreOrderSkillReq()
        CASetPreOrderSkillReq.UpdatePreOrderSkill.DeckType = DeckType
        for index,hero in enumerate(hero_list[:3],start=1):
            temp= protocol_pb2.MPreOrderSkill()
            temp.Sequence = index
            temp.HeroUniqueID = int(hero)
            temp.SkillType = random.choice([2,3])
            CASetPreOrderSkillReq.UpdatePreOrderSkill.PreOrderSkillDatas.append(temp)

        isSend = self.game.Game.SendPacket(CASetPreOrderSkillReq)
        self.WaitResult()
        return isSend

    def Req_CAOpenItemBoxReq(self,ItemUID,OpenCount=1,SelectRewardItemID=0):
        CAOpenItemBoxReq = protocol_pb2.CAOpenItemBoxReq()
        CAOpenItemBoxReq.ItemUID = ItemUID
        CAOpenItemBoxReq.OpenCount = OpenCount
        CAOpenItemBoxReq.SelectRewardItemID = SelectRewardItemID
        isSend = self.game.Game.SendPacket(CAOpenItemBoxReq)
        self.WaitResult()
        return isSend
    def Req_CAPlaySpeedReq(self,SpeedBoost=False):
        CAPlaySpeedReq = protocol_pb2.CAPlaySpeedReq()
        CAPlaySpeedReq.SpeedBoost = SpeedBoost
        isSend = self.game.Game.SendPacket(CAPlaySpeedReq)
        #self.WaitResult()
        return isSend
    def Req_CALeaveStageReq(self,StageId):
        CALeaveStageReq = protocol_pb2.CALeaveStageReq()
        CALeaveStageReq.IsRetry =False
        CALeaveStageReq.IsNextStage =True
        CALeaveStageReq.StageId = StageId
        CALeaveStageReq.IsChangeLevel = True
        isSend = self.game.Game.SendPacket(CALeaveStageReq)
        self.WaitResult()
        return isSend
    def Req_CAContentsUnlockReq(self,content_list):
        CAContentsUnlockReq = protocol_pb2.CAContentsUnlockReq()
        for content_id in content_list:
            CAContentsUnlockReq.ContentsIDs.append(content_id)
        isSend = self.game.Game.SendPacket(CAContentsUnlockReq)
        self.WaitResult()
        return isSend

    def Req_CAIndividualMissionRewardReq(self,mission_id):
        CAIndividualMissionRewardReq = protocol_pb2.CAIndividualMissionRewardReq()
        CAIndividualMissionRewardReq.MissionID = mission_id
        isSend = self.game.Game.SendPacket(CAIndividualMissionRewardReq)
        self.WaitResult()
        return isSend
    def Req_CAIndividualMissionRewardAllReq(self,PeriodType=0):
        CAIndividualMissionRewardAllReq = protocol_pb2.CAIndividualMissionRewardAllReq()
        CAIndividualMissionRewardAllReq.PeriodType = PeriodType
        isSend = self.game.Game.SendPacket(CAIndividualMissionRewardAllReq)
        return isSend
    def Req_CAGuideQuestMissionRewardReq(self,mission_id):
        CAGuideQuestMissionRewardReq = protocol_pb2.CAGuideQuestMissionRewardReq()
        CAGuideQuestMissionRewardReq.MissionTID = mission_id
        isSend = self.game.Game.SendPacket(CAGuideQuestMissionRewardReq)
        self.WaitResult()
        return isSend
    def Req_CAEventMissionRewardReq(self,mission_id):
        CAEventMissionRewardReq = protocol_pb2.CAEventMissionRewardReq()
        CAEventMissionRewardReq.MissionTID = mission_id
        isSend = self.game.Game.SendPacket(CAEventMissionRewardReq)
        self.WaitResult()
        return isSend

    def Req_CALevelUpRewardReq(self, RewardStep):
        CALevelUpRewardReq = protocol_pb2.CALevelUpRewardReq()
        CALevelUpRewardReq.RewardStep = RewardStep
        isSend = self.game.Game.SendPacket(CALevelUpRewardReq)
        return isSend
    def Req_CABuyShopGoodsReq(self, good_id,count,UseSubEtc=0):
        CABuyShopGoodsReq = protocol_pb2.CABuyShopGoodsReq()
        CABuyShopGoodsReq.ShopGoodsTID = good_id
        CABuyShopGoodsReq.BuyCount =count
        CABuyShopGoodsReq.UseSubEtc =UseSubEtc
        isSend = self.game.Game.SendPacket(CABuyShopGoodsReq)
        self.WaitResult()
        return isSend
    def Req_CACollectionBookRewardReq(self, id_list,CategoryType=1):
        CACollectionBookRewardReq = protocol_pb2.CACollectionBookRewardReq()
        for id in id_list:
            CACollectionBookRewardReq.GroupTID.append(id)
        CACollectionBookRewardReq.CategoryType = CategoryType
        CACollectionBookRewardReq.IsFinished =True
        isSend = self.game.Game.SendPacket(CACollectionBookRewardReq)
        self.WaitResult()
        return isSend
    def Req_CAItemReinforceReq(self, ItemUID,TargetReinforceLevel):#装备强化
        CAItemReinforceReq = protocol_pb2.CAItemReinforceReq()
        CAItemReinforceReq.ItemUID.append(ItemUID)
        CAItemReinforceReq.TargetReinforceLevel = TargetReinforceLevel
        CAItemReinforceReq.Skip =False
        CAItemReinforceReq.IsMulti = False
        isSend = self.game.Game.SendPacket(CAItemReinforceReq)
        self.WaitResult()
        return isSend
    def Req_CAHeroEquipItemReq(self, HeroUniqueId,EquipSlotType,SrcItemUniqueId):#穿戴装备
        CAHeroEquipItemReq = protocol_pb2.CAHeroEquipItemReq()
        temp = protocol_pb2.MChangeHeroEquip()
        temp.HeroUniqueId = HeroUniqueId
        temp.EquipSlotType = EquipSlotType
        temp.SrcItemUniqueId = int(SrcItemUniqueId)
        CAHeroEquipItemReq.ChangeHeroEquips.append(temp)
        isSend = self.game.Game.SendPacket(CAHeroEquipItemReq)
        self.WaitResult()
        return isSend
    def Req_CARepetitionBattleEnterStageReq(self, stage_id,battle_count=30):
        msg ="""{"BattleOption":{"BattleEndOption":{"LoseBattle":true,"NoRotationHero":true,"UseKeyItembox":true,"BattleCount":2},"BattleCommonOption":{"UseChangeSkillPriority":true,"UseHeroRotation":true,"RotationHeroRank":[1,2,3,4,5,6],"LowRankFirst":false,"IsBoost":true},"HeroRotationOption":[{"DeckType":6,"RotationSlotIndex":[0,1,2,3]},{"DeckType":606},{"DeckType":607},{"DeckType":616},{"DeckType":617},{"DeckType":618}],"ReserveSkills":[{"DeckType":6},{"DeckType":606},{"DeckType":607},{"DeckType":616},{"DeckType":617},{"DeckType":618}],"ModeType":1,"ItemAutoDisassemblyOption":{"DisassemblyOptions":[{"DisassemblyPartType":1,"Use":false,"Star":[1],"Grade":[1],"SubOptionCounts":[1],"MainStatOptions":[12,10,11,16,15,6,5,8,7,13]},{"DisassemblyPartType":2,"Use":false,"Star":[1],"Grade":[1],"SubOptionCounts":[1],"MainStatOptions":[18,17,16,15,6,5,8,7,14]},{"DisassemblyPartType":3,"Use":false,"Star":[1],"Grade":[1]}]}},"StageId":200001}"""
        CARepetitionBattleEnterStageReq = protocol_pb2.CARepetitionBattleEnterStageReq()
        json_format.Parse(msg,CARepetitionBattleEnterStageReq)
        CARepetitionBattleEnterStageReq.BattleOption.BattleEndOption.BattleCount = battle_count
        CARepetitionBattleEnterStageReq.StageId =stage_id
        isSend = self.game.Game.SendPacket(CARepetitionBattleEnterStageReq)
        self.WaitResult()
        return isSend
    def Req_CAChangeRepetitionBackgroundModeReq(self):
        CAChangeRepetitionBackgroundModeReq = protocol_pb2.CAChangeRepetitionBackgroundModeReq()
        isSend = self.game.Game.SendPacket(CAChangeRepetitionBackgroundModeReq)
        return isSend

    def Req_CARepetitionBattleResultReq(self):#请求重复战斗结果数据
        CARepetitionBattleResultReq = protocol_pb2.CARepetitionBattleResultReq()
        isSend = self.game.Game.SendPacket(CARepetitionBattleResultReq)
        self.WaitResult()
        return isSend

    def Req_CAConditionGoodsReq(self):
        CAConditionGoodsReq = protocol_pb2.CAConditionGoodsReq()
        isSend = self.game.Game.SendPacket(CAConditionGoodsReq)
        self.WaitResult()
        return isSend
    def Req_CAGetShopReq(self):
        CAGetShopReq = protocol_pb2.CAGetShopReq()
        isSend = self.game.Game.SendPacket(CAGetShopReq)
        self.WaitResult()
        return isSend
    def Req_CAReceiveBattlePassRewardReq(self,EventMainTID,ReceiveLevel,IsPremiumReward=False):
        CAReceiveBattlePassRewardReq = protocol_pb2.CAReceiveBattlePassRewardReq()
        CAReceiveBattlePassRewardReq.EventMainTID = EventMainTID
        CAReceiveBattlePassRewardReq.ReceiveLevel = ReceiveLevel
        CAReceiveBattlePassRewardReq.IsPremiumReward = IsPremiumReward
        isSend = self.game.Game.SendPacket(CAReceiveBattlePassRewardReq)
        self.WaitResult()
        return isSend
    def Req_CAStageAchievementRewardReq(self,LandMarkID,Difficulty=0):
        CAStageAchievementRewardReq = protocol_pb2.CAStageAchievementRewardReq()
        CAStageAchievementRewardReq.LandMarkID = LandMarkID
        CAStageAchievementRewardReq.Difficulty = Difficulty
        isSend = self.game.Game.SendPacket(CAStageAchievementRewardReq)
        self.WaitResult()
        return isSend
    def Req_CAHeroReinforceReq(self,TargetHeroUIDs,MaterialHeroUIDs,EstimatedCost=0):
        CAHeroReinforceReq = protocol_pb2.CAHeroReinforceReq()
        CAHeroReinforceReq.TargetHeroUIDs.append(TargetHeroUIDs)
        for id in MaterialHeroUIDs:
            CAHeroReinforceReq.MaterialHeroUIDs.append(id)
        CAHeroReinforceReq.EstimatedCost = EstimatedCost
        isSend = self.game.Game.SendPacket(CAHeroReinforceReq)
        self.WaitResult()
        return isSend
    def Req_CAHeroComposeReq(self,MaterialUIDs,IsFixed=False):
        CAHeroComposeReq = protocol_pb2.CAHeroComposeReq()
        temp = protocol_pb2.MHeroCompose()
        for id in MaterialUIDs:
            temp.MaterialUIDs.append(id)
        temp.IsFixed = IsFixed
        temp.ResultHeroTID = 0
        CAHeroComposeReq.HeroComposes.append(temp)
        isSend = self.game.Game.SendPacket(CAHeroComposeReq)
        self.WaitResult()
        return isSend
    def Req_CAConversionReq(self,ConversionTID,ConversionCount=1):
        CAConversionReq = protocol_pb2.CAConversionReq()
        CAConversionReq.ConversionTID = ConversionTID
        CAConversionReq.ConversionCount = ConversionCount
        isSend = self.game.Game.SendPacket(CAConversionReq)
        self.WaitResult()
        return isSend
    def Req_CAHeroEvolutionReq(self,HeroUID):
        CAHeroEvolutionReq = protocol_pb2.CAHeroEvolutionReq()
        CAHeroEvolutionReq.HeroUID = HeroUID
        isSend = self.game.Game.SendPacket(CAHeroEvolutionReq)
        self.WaitResult()
        return isSend
    def Req_CAFormationLevelUpReq(self,FormationGroup,Level):
        CAFormationLevelUpReq = protocol_pb2.CAFormationLevelUpReq()
        CAFormationLevelUpReq.FormationGroup = FormationGroup
        CAFormationLevelUpReq.Level = Level
        isSend = self.game.Game.SendPacket(CAFormationLevelUpReq)
        self.WaitResult()
        return isSend
    def Req_CAHeroFirstTalkReq(self,PCGroupTID):
        CAHeroFirstTalkReq = protocol_pb2.CAHeroFirstTalkReq()
        CAHeroFirstTalkReq.PCGroupTID = PCGroupTID
        isSend = self.game.Game.SendPacket(CAHeroFirstTalkReq)
        self.WaitResult()
        return isSend
    def Req_CAAgitTalkHeroReq(self,PCGroupTID):
        CAAgitTalkHeroReq = protocol_pb2.CAAgitTalkHeroReq()
        CAAgitTalkHeroReq.PCGroupTID = PCGroupTID
        isSend = self.game.Game.SendPacket(CAAgitTalkHeroReq)
        self.WaitResult()
        return isSend
    def Req_CAAccumulatePurchaseRewardReq(self,ReceiveDay):
        CAAccumulatePurchaseRewardReq = protocol_pb2.CAAccumulatePurchaseRewardReq()
        CAAccumulatePurchaseRewardReq.ReceiveDay = ReceiveDay
        isSend = self.game.Game.SendPacket(CAAccumulatePurchaseRewardReq)
        self.WaitResult()
        return isSend